package com.itheima.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.domain.Food;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.FoodMapper;
import com.itheima.service.FoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/*
    膳食服务层实现类
 */
@Service(interfaceClass = FoodService.class)
@Transactional
public class FoodServiceImpl implements FoodService {

    //注入foodMapper
    @Autowired
    private FoodMapper foodMapper;


    //上传文件
    public void add(List<Food> foodList) {
        if(foodList != null && foodList.size() > 0){
            for (Food food : foodList) {
                //判断膳食编号是否已经进行了膳食设置
                long countBySerialNumber = foodMapper.findCountBySerialNumber(food.getSerialNumber());
                if (countBySerialNumber > 0) {
                    //已经进行了膳食设置,执行更新操作
                    foodMapper.editNumberBySerialNumber(food);
                }else {
                    //没有进行膳食设置,执行插入操作
                    foodMapper.add(food);
                }
            }
        }
    }


    //添加膳食项
    public void addition(Food food) {
        //调用持久层方法,和上传文件的add方法一致,直接调用
        foodMapper.add(food);
    }


    //分页查询膳食信息
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();//当前页码
        Integer pageSize = queryPageBean.getPageSize();//每页条目数
        String queryString = queryPageBean.getQueryString();//查询条件
        //调用分页插件方法进行分页
        PageHelper.startPage(currentPage,pageSize);
        //调用持久层接口进行条件查询
        Page<Food> page = foodMapper.findPage(queryString);
        //返回结果
        return new PageResult(page.getTotal(),page.getResult());
    }


    //编辑框回显
    public Food findById(int id) {
        //调用持久层接口
        Food food = foodMapper.findById(id);
        //返回结果
        return food;
    }


    //编辑膳食项
    public void edit(Food food) {
        //调用持久层接口
        foodMapper.edit(food);
    }


    //删除膳食项
    public void delete(int id) {
        if (foodMapper.findByFoodId(id) > 0){
            throw new RuntimeException("存在外键约束,删除失败...");
        }
        //调用持久层接口,没有关联表格,不用进行判断
        foodMapper.delete(id);
    }

    //健康干预显示膳食信息
    public List<Food> findAllFood() {
        //调用持久层
        List<Food> list = foodMapper.findAllFood();
        //返回结果
        return list;
    }
}
